<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2019/8/14
 * Time: 17:44
 */
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Redis;
class BasicController extends Controller
{
    /**
     * 用户ID
     * @var null
     */
    protected $userId = null;
    /**
     * 用户信息
     * @var array
     */
    protected $userInfo = [];
    /**
     * openid
     * @var null
     */
    protected $openid = null;
    /**
     * unionid
     * @var null
     */
    protected $unionid = null;

    /**
     * 初始化
     * Controller constructor.
     */
    public function __construct()
    {
        $this->getToken();
    }

    /**
     * 获取用户信息
     */
    public function getToken()
    {
        $request = app("request");
        $token = $request->header("token")?:$request->input("token");
        if (!empty($token) && Redis::connection('default')->exists($token)){
            $user = Redis::connection('default')->get($token);
            $this->userInfo = json_decode($user,true);
            $this->setUserId();
        }
    }

    /**
     * 设置用户ID
     */
    public function setUserId()
    {
        $this->userId = (int)$this->userInfo['id']??null;
    }

    /**
     * 请求成功
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function success($data=[])
    {
        return response()->json(['code'=>0,'msg'=>'请求成功','data'=>$data],200,[],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }

    /**
     * 请求失败
     * @param $code
     * @param $msg
     * @return \Illuminate\Http\JsonResponse
     */
    public function fail($code,$msg)
    {
        return response()->json(['code'=>$code,'msg'=>$msg],200,[],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }
}